﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace MyWebBrowser.Screenshot
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public Rectangle GetRect()
        {
            string[] strs = this.txtRect.Text.Split(',');
            return new Rectangle(int.Parse(strs[0]), int.Parse(strs[1]), int.Parse(strs[2]), int.Parse(strs[3]));
        }

        private void btnUrl_Click(object sender, EventArgs e)
        {
            this.Enabled = false;
            using (WebBrowser wb = new WebBrowser())
            {
                wb.Width = 1000;
                wb.ScrollBarsEnabled = false;
                wb.ScriptErrorsSuppressed = true;
                wb.Navigate(this.txtUrl.Text);
                wb.DocumentCompleted += (s1,e1)=>
                {
                    wb.Stop();
                    this.txtSourceSize.Text = string.Format("{0},{1}", wb.Document.Body.ScrollRectangle.Width, wb.Document.Body.ScrollRectangle.Height);
                    wb.Height = wb.Document.Body.ScrollRectangle.Height;

                    var rect = this.GetRect();
                    if (rect.Width == 0 || rect.Height == 0)
                    {
                        rect.Location = new Point(0, 0);
                        rect.Size = new Size(wb.Document.Body.ScrollRectangle.Width, wb.Document.Body.ScrollRectangle.Height);
                    }

                    if (rect.Height > 0)
                    {
                        Bitmap bitmap = new Bitmap(rect.Width, rect.Height);
                        wb.DrawToBitmap(bitmap, rect);
                        this.picImage.Image = bitmap;
                    }
                    else
                        this.picImage.Image = null;
                };
                do
                {
                    Application.DoEvents();
                } while (wb.ReadyState != WebBrowserReadyState.Complete);
            }
            this.Enabled = true;
        }

        private void btnHtml_Click(object sender, EventArgs e)
        {

        }
    }
}
